package com.lcy.redismessage.service;

import com.lcy.redismessage.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 消息处理service
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2018-05-22 17:08
 **/
@Service
@Slf4j
public class MessageService {

    private static Logger logger = LoggerFactory.getLogger(MessageService.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${channelname}")
    private String channelName;

    @Value("${queuename}")
    private String queueName;

    private CountDownLatch latch;
    @Autowired
    public MessageService(CountDownLatch latch) {
        this.latch = latch;
    }

    /**
     * 价格趋势和市场队列消息接收方法
     * @param jsonMsg
     */
    public void priceReceive(String jsonMsg) {
        log.info("[开始消费REDIS消息队列数据...]");
        try{
            System.out.println("拉取内容：" + jsonMsg);

            log.info("[消费REDIS消息队列数据成功.]");
        }catch(Exception e){
            log.error("[消费REDIS消息队列数据失败，失败信息:{}]", e.getMessage());
        }
        latch.countDown();
    }

    /**
     * redis发布消息
     *
     * @param message
     */
    public void sendTopicMessage(String message) {
        redisTemplate.convertAndSend(channelName, message);
    }

    /**
     * 处理redis消息队列
     */
    public void dealMsg() {
        String message = redisUtil.rightPop(queueName, 1, TimeUnit.MINUTES);
        if (message != null) {
            logger.info("redis--queue:" + queueName + "  body:" + message);
        }
    }

    /**
     * @param message
     */
    public void sendQueueMessage(String message) {
        redisUtil.leftPush(queueName, message);
    }
}
